package com.lyz.models;

import com.lyz.utils.SessionIdGenerator;
import com.lyz.utils.impl.DefaultSessionIdGenerator;
import lombok.Data;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Data
public class Session<T> {

    private final Object sessionId;

    private Long cTime;

    private final Map<String, Object> data;

    private final T userInfo;

    private static SessionIdGenerator generator = new DefaultSessionIdGenerator();

    public Session(T userInfo) {
        this.sessionId = generator.generate();
        this.cTime = System.currentTimeMillis();
        this.data = new HashMap<>();
        this.userInfo = userInfo;
    }

    public synchronized void setAttribute(String attributeKey, Object attributeValue) {
        data.put(attributeKey, attributeValue);
    }

    public Object getAttribute(String attributeKey) {
        return data.get(attributeKey);
    }

    public void refreshSession() {
        this.cTime = System.currentTimeMillis();
    }

    public void clearAttributes() {
        this.data.clear();
    }

    public Collection<Object> getAttributes() {
        return data.values();
    }

}
